<template>
    <el-card class="card">
        <template #header>
            <div class="card-header flex justify-between">
                <div style="align-content: center;">文件上传</div>
                <el-upload :action="fileUrl" :show-file-list="false" :on-success="onSuccess">
                    <el-button type="primary">选择文件</el-button>
                </el-upload>
            </div>
        </template>
        <p class="text item">当前名称:{{ originalFilename || '无' }}</p>

        <p class="text item">转换后文件名:{{ newFilename || '无' }}</p>
        <el-input v-model="newFilename" />

        <el-button @click="handleConvert">文件转码</el-button>
        <el-button @click="download">文件下载</el-button>
    </el-card>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'

const fileUrl = ref<string>(import.meta.env.VITE_FILE_URL)
// 上传文件
const fileMark = ref<string>('')
const originalFilename = ref<string>('')
const onSuccess: UploadProps['onSuccess'] = (res, file) => {
    originalFilename.value = res.name
    fileMark.value = res.mark
}
// 文件转码
const newFilename = ref<string>('测试.mp3')
async function handleConvert() {
    const params = new URLSearchParams({ mark: '0c8c0d00da863a2bc2b334700.ogg', name: newFilename.value }).toString();
    const response = await fetch(`http://localhost:5173/file/convert?${params}`);
    const res = await response.text()
    ElMessage.success(res)
}
// 文件下载
async function download() {
    const params = new URLSearchParams({ name: newFilename.value }).toString();
    // const response = await fetch(`http://localhost:5173/file/download?${params}`);
    // const blob = await response.blob(); // 获取文件的二进制数据
    // const blobUrl = URL.createObjectURL(blob);
    // window.open(blobUrl); // 直接打开 Blob URL
    // URL.revokeObjectURL(blobUrl); // 释放 URL
    const link = document.createElement('a');
    link.href = `http://101.201.103.220:7777/file/download?${params}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

</script>
<style lang="less" scoped>
.card {
    width: 500px;
    height: 500px;
}
</style>